<?php

class Pictet2_Controllers_Default extends Pictet2_Controllers_Abstract {
	
	private $_thumbnailer;
	private $_metahandler;
	private $_view;
	
	public function __construct() {
		if(!($engine = Pictet2_Settings::getSetting("ThumbnailEngine"))) {
			$engine = "Gd";
		}
		$class = Pictet2::getClassName("Thumbnailer_" . $engine);
		$this->_view = Pictet2_Registry::getRegistry("view");
		$this->_thumbnailer = new $class();
		$this->_metahandler = new Pictet2_Metahandlers_Xml();
		/*
		$dirIterator = new Pictet2_Iterators_Filters_Default(new Pictet2_Iterators_Directory(".", $this->_thumbnailer), $this->_thumbnailer);
		
		foreach($dirIterator as $file) {

			$files[] = $file->getFilename();
		}
		*/

		$dir = opendir(".");
		while($file = readdir($dir)) {
			if($this->_thumbnailer->isValid($file)) {
				$files[] = $file;
			}
			if(is_dir($file)) {
				if($file[0] != ".") {
					$tmpdir = opendir($file);
					while(!$firstfile && $tmpfile = readdir($tmpdir)) {
						if($this->_thumbnailer->isValid($tmpfile)) {
							$firstfile = $tmpfile;
						}
					}
					if($firstfile) {
						$dirs[] = $file;
						$fileinfo = pathinfo($firstfile);
						if(!file_exists($file . DS . ".thumbs" . DS . ".dirpreview.jpg")) {
							$this->_thumbnailer->directoryPreview($firstfile, $file);
						}
						$firstfile = "";
					}
				}
			}
		}
		$this->_view->assign("subDirs", $dirs);
		$length = 12;
		$offset = (GALLERY_PAGE-1)*$length;
		if($files) {
			$gallery = array_splice($files, $offset, $length);
			foreach($gallery as $file) {
				if($this->_metahandler->checkMetaModiefied($file) || !file_exists(".thumbs" . DS . $file)) {
					$this->_thumbnailer->makeThumb($file);
				}
			}
			$this->_view->assign("files", $gallery);
		}
		
		if(GALLERY_PAGE > 1) {
			$this->_view->assign("previousPage", GALLERY_PAGE-1);
		}
		if($files[$offset]) {
			$this->_view->assign("nextPage", GALLERY_PAGE+1);
		}
		$this->_view->assign("lastPage",ceil((sizeof($files)-1)/$length)+1);
		
		$this->_view->render("gallery");
	}
	
	public function __destruct() {
		$this->_metahandler->saveMetadata();
	}
	
}